/*
 * ExtFileFilter.java
 *
 *  created: 25.10.2011
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */
package cz.mp.k3bg.misc;

import cz.mp.util.FileUtils;
import cz.mp.util.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Martin Pokorný
 * @version 0.1
 */
public class ExtFileFilter extends FileFilter {
    
    private ArrayList<String> extensions = new ArrayList<String>();
    /** Základní část popisu filtru, bez přípon. */
    private String baseDescription;    
    /** Výsledný popis. */
    private String description;
    

    /**
     * 
     * @param baseDescription
     * @param extensions 
     */
    public ExtFileFilter(String baseDescription, List<String> extensions) {
        this(baseDescription, extensions.toArray(new String[0]));   
    }
    
    /**
     * 
     * @param baseDescription
     * @param extensions 
     */
    public ExtFileFilter(String baseDescription, String... extensions) {
        this.baseDescription = baseDescription;
        if (extensions != null) {
            Collections.addAll(this.extensions, extensions);
        }
        setUpDescription();        
    }

    /**
     * 
     * @return 
     */
    private String createExtensionsText() {
        if (extensions.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < extensions.size()-1; i++) {
            sb.append("*.").append(extensions.get(i));
            sb.append(", ");
        }
        sb.append("*.").append(extensions.get(extensions.size()-1));
        return sb.toString();
    }
    
    /**
     * 
     */
    private void setUpDescription() {
        description = baseDescription;
        String exts = createExtensionsText();
        if (! exts.isEmpty()) {
            description = description + " (" + exts + ")";
        }
    }
    
    /**
     * 
     * @return 
     */
    public List<String> getExtensionsList() {
        return Collections.unmodifiableList(extensions);
    }
    
    @Override
    public boolean accept(File file) {
        // podmínka musí být -- ve Windows, když se klikne na [Tento počítač] v postranním panelu ...
        if (StringUtils.isBlank(file.getName())) {   
            return true;
        }
        boolean hasExt = FileUtils.hasFileExtension(file.getName(), extensions);
        boolean isDir = file.isDirectory();
        return isDir || hasExt;
    }

    @Override
    public String getDescription() {
        return description;
    }
    
}   // ExtFileFilter.java

